package repository

import (
	"fmt"
	"hcy-api/structs/lms"
	"hcy-api/structs/tables"
	"lms/global"
)

var ExamDB = new(examDB)

type examDB struct {
}

func (d examDB) FindQuestionById(id int64) (m tables.Question, err error) {
	err = global.DB.Where(&tables.Question{Id: id}).Find(&m).Error
	return
}

func (d examDB) FindQuestionFolderAll() (li []tables.QuestionFolder, err error) {
	err = global.DB.Model(&tables.QuestionFolder{}).Find(&li).Error
	return
}

func (d examDB) FindQuestionPage(in lms.SearchQuestion) (li []tables.Question, total int64, err error) {
	tx := global.DB.Model(&tables.Question{}).Where("title like ? ", fmt.Sprintf("%%%s%%", in.Name))
	if in.FolderId != 0 {
		tx.Where("folder_id = ? ", in.FolderId)
	}
	err = tx.Count(&total).Offset((in.PageNum - 1) * in.PageSize).Limit(in.PageSize).Find(&li).Error
	return
}
func (d examDB) CreateQuestionFolder(m *tables.QuestionFolder) (err error) {
	err = global.DB.Save(m).Error
	return
}

func (d examDB) FindQuestionFolderByDepth(depth string) (m tables.QuestionFolder, err error) {
	err = global.DB.Model(&tables.QuestionFolder{}).Where(tables.QuestionFolder{PathDepth: depth}).Find(&m).Error
	return
}

func (d examDB) FindExamPaperPage(in lms.SearchExamPaperPage) (li []tables.ExamPapers, total int64, err error) {
	err = global.DB.Model(&tables.ExamPapers{}).Where("code like ?",
		fmt.Sprintf("%%%s%%", in.Code)).Count(&total).
		Offset((in.PageNum - 1) * in.PageSize).Limit(in.PageSize).Find(&li).Error
	return
}

// FindQuestionListByPaperId 根据试卷ID查询试卷关联的题目列表
func (d examDB) FindQuestionListByPaperId(id int64) (li []tables.MapExamQuestions, err error) {
	err = global.DB.Model(&tables.MapExamQuestions{}).
		Where(&tables.MapExamQuestions{ExamId: id}).Find(&li).Error
	return
}

// FindExamPaperById 根据试卷ID查询试卷信息
func (d examDB) FindExamPaperById(id int64) (m tables.ExamPapers, err error) {
	err = global.DB.Model(&tables.ExamPapers{}).Where(&tables.ExamPapers{Id: id}).First(&m).Error
	return
}

// InsertExamResult 写入考试结果映射，一般是用户点击交卷时触发
func (d examDB) InsertExamResult(li []tables.ExamResult) (err error) {
	err = global.DB.Model(&tables.ExamResult{}).CreateInBatches(li, len(li)).Error
	return
}
